package com.emm.yixun.customer.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.basic.service.CustTagService;
import com.emm.yixun.basic.service.CustomerAnswerService;
import com.emm.yixun.basic.service.CustomerProjectAnswerService;
import com.emm.yixun.basic.service.CustomerProjectQuestionService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.ProjectAnswerService;
import com.emm.yixun.basic.service.ProjectQuestionService;
import com.emm.yixun.basic.service.ProjectQuestionnaireService;
import com.emm.yixun.basic.service.TagValueService;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.CustomerAnswer;
import com.emm.yixun.common.model.CustomerAnswerInfo;
import com.emm.yixun.common.model.CustomerProjectQuestion;
import com.emm.yixun.common.model.ProjectAnswer;
import com.emm.yixun.common.model.ProjectQuestion;
import com.emm.yixun.common.model.ProjectQuestionnaire;
import com.emm.yixun.common.model.dto.CustTagDto;
import com.emm.yixun.common.model.dto.CustomerAnswerDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.CustomerProjectAnswerDto;
import com.emm.yixun.common.model.dto.CustomerProjectQuestionDto;
import com.emm.yixun.common.model.dto.ProjectAnswerDto;
import com.emm.yixun.common.model.dto.ProjectQuestionDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsValidEnum;
import com.emm.yixun.customer.service.CustomerAnswerServiceFacade;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("customerAnswerServiceFacade")
@WebService(name="com.emm.yixun.customer.service.CustomerAnswerServiceFacade")
public class CustomerAnswerServiceFacadeImpl implements CustomerAnswerServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private CustomerAnswerService service;
	
	@Autowired
	private CustomerProjectQuestionService customerProjectQuestionService;
	
	@Autowired
	private CustomerProjectAnswerService customerProjectAnswerService;
	
	@Autowired
	private CustomerAnswerService customerAnswerService;
	
	@Autowired
	private ProjectQuestionService projectQuestionService;
	
	@Autowired
	private ProjectQuestionnaireService projectQuestionnaireService;
	
	@Autowired
	private ProjectAnswerService projectAnswerService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private CustTagService custTagService;
	
	@Autowired
	private TagValueService tagValueService; 

	@Override
	public Response<CustomerAnswerDto> save(CustomerAnswerDto dto) {
		Response<CustomerAnswerDto> response=new Response<CustomerAnswerDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			CustomerAnswerDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(CustomerAnswerDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			CustomerAnswerDto mDto=new CustomerAnswerDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<CustomerAnswer> findById(Long id) {
		Response<CustomerAnswer> response=new Response<CustomerAnswer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			CustomerAnswer entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<CustomerAnswer> findByDto(CustomerAnswerDto dto) {
		ResponseList<CustomerAnswer> response=new ResponseList<CustomerAnswer>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<CustomerAnswer> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<CustomerAnswer> findPageByDto(CustomerAnswerDto dto, Integer begin,Integer row) {
		Page<CustomerAnswer> response=new Page<CustomerAnswer>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<CustomerAnswer> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}
	//项目问卷问题ID对应客户问卷问题ID
	private Map<Long, Long> questionMap;
	//项目问卷答案ID对应客户问卷答案ID
	private Map<Long, Long> answerMap;

	@Override
	public Response<CustomerAnswer> add(CustomerAnswerInfo info) {
		Response<CustomerAnswer> response=new Response<CustomerAnswer>();
		try {
			//当客户ID为-1时，表示从H5保存，不需要删除
			if(info.getCustomerId() != -1L) {
				//先删除原纪录
				boolean flag1 = deleteQuestion(info.getProjectQuestionnaireId(), info.getCustomerId());
				if(!flag1) {
					response.fail("0000", "问卷保存失败");
				}
			}
			//先保存客户问卷及答案
			boolean flag2 = saveQuestion(info);
			if(!flag2) {
				response.fail("0000", "问卷保存失败");
			}
			//保存客户回答的答案
			boolean flag3 = saveCustomerAnswer(info);
			if(!flag3){
				response.fail("0000", "问卷保存失败");
			}
			response.success(new CustomerAnswer());
			
			//20180525需求：有客户ID时，自动变成客户等级
/*			if(info.getCustomerId() != -1L) {
				Customer customer = customerService.selectById(info.getCustomerId());
				if("4".equals(customer.getIntentionLevel()) || "5".equals(customer.getIntentionLevel())) {
					CustomerDto cusDto = new CustomerDto();
					cusDto.setId(customer.getId());
					cusDto.setIntentionLevel("3");
					customerService.update(cusDto);
				}
			}
*/
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存问卷失败：{}",e);
			
			e.printStackTrace();
		}
		return response;
	}
	/**
	 * 删除客户问卷原表记录
	 * @param pqId
	 * @return
	 */
	private boolean deleteQuestion(Long pqId, Long customerId){
		if(pqId == null){
			return false;
		}
		//获取问卷信息
		ProjectQuestionnaire naire = projectQuestionnaireService.selectById(pqId);
		if(naire == null) {
			return false;
		}
		//当问卷类型为题库时，去掉问卷ID条件，删除该客户全部已答题目
		if("1".equals(naire.getType())) {
			pqId = null;
		}
		//删除客户问卷问题
		CustomerProjectQuestionDto entity1 = new CustomerProjectQuestionDto();
		entity1.setProjectQuestionnaireId(pqId);
		entity1.setCustomerId(customerId);
		customerProjectQuestionService.destroy(entity1);
		
		//删除客户问卷答案
		CustomerProjectAnswerDto entity2 = new CustomerProjectAnswerDto();
		entity2.setProjectQuestionnaireId(pqId);
		entity2.setCustomerId(customerId);
		customerProjectAnswerService.destroy(entity2);
		
		//删除客户回答的答案
		deleteCustomerAnswer(pqId, customerId, naire.getType());
		
		return true;
	}
	/**
	 * 保存客户回答的问卷问题
	 * @param info
	 * @return
	 */
	private boolean saveQuestion(CustomerAnswerInfo info) {
		//查询项目问卷问题
		ProjectQuestionDto entity = new ProjectQuestionDto();
		entity.setProjectQuestionnaireId(info.getProjectQuestionnaireId());
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		entity.setIsValid(IsValidEnum.VALID.getNo());
		List<ProjectQuestion> pqList = projectQuestionService.selectListByDto(entity);
		if(pqList == null){
			return false;
		}
		questionMap = new HashMap<Long, Long>();
		answerMap = new HashMap<Long, Long>();
		//循环保存问卷问题
		for(ProjectQuestion pq : pqList){
			CustomerProjectQuestionDto dto = new CustomerProjectQuestionDto();
			BeanUtils.copyProperties(pq, dto);
			dto.setProjectQuestionId(pq.getId());
			dto.setCustomerId(info.getCustomerId());
			dto.setCustomerName(info.getCustomerName());
			dto.setCustomerPhone(info.getCustomerPhone());
			dto.setCreateUser(info.getCreateUser());
			dto.setCreateTime(info.getCreateTime());
			CustomerProjectQuestionDto cp = customerProjectQuestionService.create(dto);
			//设置项目问卷问题ID对应客户问卷问题ID
			questionMap.put(pq.getId(), cp.getId());
			//保存问题答案
			saveAnswer(info.getProjectQuestionnaireId(), cp.getId(), pq.getId(), info.getCustomerId());
		}
		return true;
	}
	/**
	 * 保存客户回答的问卷答案
	 * @param cpqId
	 * @param pqId
	 * @return
	 */
	private boolean saveAnswer(Long projectQuestionnaireId, Long cpqId, Long pqId, Long customerId){
		ProjectAnswerDto entity = new ProjectAnswerDto();
		entity.setProjectQuestionId(pqId);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		entity.setIsValid(IsValidEnum.VALID.getNo());
		List<ProjectAnswer> paList = projectAnswerService.selectListByDto(entity);
		if(paList == null){
			return false;
		}
		//循环保存问题答案
		for(ProjectAnswer pa : paList){
			CustomerProjectAnswerDto dto = new CustomerProjectAnswerDto();
			BeanUtils.copyProperties(pa, dto);
			dto.setProjectQuestionnaireId(projectQuestionnaireId);
			dto.setCustomerProjectQuestionId(cpqId);
			dto.setProjectQuestionId(pqId);
			dto.setProjectAnswerId(pa.getId());
			dto.setCustomerId(customerId);
			CustomerProjectAnswerDto cpa = customerProjectAnswerService.create(dto);
			//设置项目问卷答案ID对应客户问卷答案ID
			answerMap.put(pa.getId(), cpa.getId());
		}
		return true;
	}
	/**
	 * 保存客户答案
	 * @param info
	 * @return
	 */
	private boolean saveCustomerAnswer(CustomerAnswerInfo info){
		//解析arrayJson，获取问题内容，并循环保存
		JSONArray array = JSONArray.fromObject(info.getArrayJson());
		for(int i = 0; i < array.size(); i++){
			JSONObject json = (JSONObject)array.get(i);
			//通过项目问卷问题ID获取客户回答问题ID
			Long customerProjectQuestionId = null;
			if(StringUtils.isNotBlank(json.getString("questionId"))){
				customerProjectQuestionId = questionMap.get(json.getLong("questionId"));
			}
			//通过项目问卷答案ID获取客户回答答案ID
			List<Long> answerIdList = new ArrayList<Long>();
			String answerId = json.getString("answerId");
			if(StringUtils.isNotBlank(answerId)){
				if(answerId.indexOf("[") >= 0){
					answerIdList = getAnswerIdByMap(answerId);
				}else{
					answerIdList.add(answerMap.get(Long.parseLong(answerId)));
				}
			}
			//获取答案类型
			String answerType = json.getString("answerType");
			//获取“其他”选项ID
			Long selectOther = null;
			if(StringUtils.isNotBlank(json.getString("select_other"))){
				selectOther = answerMap.get(json.getLong("select_other"));
			}
			//获取文本答案（当答案类型为文本，或者有答案选项为“其他”时）
			String answerText = null;
			if("3".equals(answerType) || selectOther != null){
				answerText = json.getString("answerText");
			}
			//当ID和文本答案都为空时，不执行保存操作
			if(answerIdList.size() == 0 && StringUtils.isBlank(answerText)){
				continue;
			}
			
			CustomerAnswerDto entity = new CustomerAnswerDto();
			entity.setCustomerId(info.getCustomerId()); //客户ID
			entity.setCustomerName(info.getCustomerName());
			entity.setCustomerPhone(info.getCustomerPhone());
			entity.setProjectQuestionnaireId(info.getProjectQuestionnaireId()); //项目问卷ID
			entity.setCustomerProjectQuestionId(customerProjectQuestionId);
			entity.setAnswerType(answerType); //答案类型
			entity.setCreateTime(info.getCreateTime());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			//当答案类型为文本答案时
			if("3".equals(answerType)){
				entity.setAnswerValue(answerText); //文本答案
				service.create(entity);
				continue;
			}
			//当答案为选项时
			for(int p = 0; p < answerIdList.size(); p++){
				Long cpaId = answerIdList.get(p);
				entity.setCustomerProjectAnswerId(cpaId);
				//当答案ID等于“其他”选项ID时，保存文本答案
				if(cpaId == selectOther){
					entity.setAnswerValue(answerText); //文本答案
				}
				service.create(entity);
			}
			//更新标签答案
			updateCustTag(json.getString("questionId"), info.getCustomerId(), answerIdList);
		}
		
		return true;
	}
	/**
	 * 获取答案ID
	 * @param answerId
	 * @return
	 */
	private List<Long> getAnswerIdByMap(String answerId){
		List<Long> answerIdList = new ArrayList<Long>();
		JSONArray array = JSONArray.fromObject(answerId);
		for(int i = 0; i < array.size(); i++){
			answerIdList.add(answerMap.get(array.getLong(i)));
		}
		return answerIdList;
	}
	
	/**
	 * 更新标签答案
	 * @param questionId
	 * @param customerId
	 * @param answerIdList
	 * @return
	 */
	private boolean updateCustTag(String questionId, Long customerId, List<Long> answerIdList) {
		//通过问题ID和客户ID获取标签答案ID
		Long cusTagId = custTagService
				.getCusTagIdByQuestionId(questionId, 
						customerId);
		//id为空，表示客户没有填写过标签，不进行标签修改操作
		if(cusTagId == null) {
			return true;
		}
		//获取答案集合
		String answers = customerProjectAnswerService.getAnswerByIds(answerIdList);
		//获取答案ID集合
		String answerIds = tagValueService.getTagValueIdByAnswer(questionId, answers);
		//更新标签答案
		CustTagDto ctDto = new CustTagDto();
		ctDto.setId(cusTagId);
		ctDto.setTagValue(answers);
		ctDto.setTagValueId(answerIds);
		custTagService.update(ctDto);
		return true;
	}

	@Override
	public Response<CustomerAnswer> edit(CustomerAnswerInfo info) {
		Response<CustomerAnswer> response=new Response<CustomerAnswer>();
		try {
			//获取问卷信息
			ProjectQuestionnaire naire = projectQuestionnaireService.selectById(info.getProjectQuestionnaireId());
			//先删除原纪录
			boolean flag1 = deleteCustomerAnswer(info.getProjectQuestionnaireId(), info.getCustomerId(), naire.getType());
			if(!flag1) {
				response.fail("0000", "问卷保存失败");
			}
			//保存客户回答的答案
			boolean flag2 = editCustomerAnswer(info);
			if(!flag2){
				response.fail("0000", "问卷保存失败");
			}
			response.success(new CustomerAnswer());
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存问卷失败：{}",e);
			e.printStackTrace();
		}
		return response;
	}
	/**
	 * 编辑客户答案
	 * @param info
	 * @return
	 */
	private boolean editCustomerAnswer(CustomerAnswerInfo info){
		//解析arrayJson，获取问题内容，并循环保存
		JSONArray array = JSONArray.fromObject(info.getArrayJson());
		for(int i = 0; i < array.size(); i++){
			JSONObject json = (JSONObject)array.get(i);
			//通过项目问卷问题ID获取客户回答问题ID
			Long customerProjectQuestionId = null;
			if(StringUtils.isNotBlank(json.getString("questionId"))){
				customerProjectQuestionId = json.getLong("questionId");
			}
			//通过项目问卷答案ID获取客户回答答案ID
			List<Long> answerIdList = new ArrayList<Long>();
			String answerId = json.getString("answerId");
			if(StringUtils.isNotBlank(answerId)){
				if(answerId.indexOf("[") >= 0){
					answerIdList = getAnswerId(answerId);
				}else{
					answerIdList.add(Long.parseLong(answerId));
				}
			}
			//获取答案类型
			String answerType = json.getString("answerType");
			//获取“其他”选项ID
			Long selectOther = null;
			if(StringUtils.isNotBlank(json.getString("select_other"))){
				selectOther = json.getLong("select_other");
			}
			//获取文本答案（当答案类型为文本，或者有答案选项为“其他”时）
			String answerText = null;
			if("3".equals(answerType) || selectOther != null){
				answerText = json.getString("answerText");
			}
			//当ID和文本答案都为空时，不执行保存操作
			if(answerIdList.size() == 0 && StringUtils.isBlank(answerText)){
				continue;
			}
			
			CustomerAnswerDto entity = new CustomerAnswerDto();
			entity.setCustomerId(info.getCustomerId()); //客户ID
			entity.setProjectQuestionnaireId(info.getProjectQuestionnaireId()); //项目问卷ID
			entity.setCustomerProjectQuestionId(customerProjectQuestionId);
			entity.setAnswerType(answerType); //答案类型
			entity.setCreateTime(info.getCreateTime());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			//当答案类型为文本答案时
			if("3".equals(answerType)){
				entity.setAnswerValue(answerText); //文本答案
				service.create(entity);
				continue;
			}
			//当答案为选项时
			for(int p = 0; p < answerIdList.size(); p++){
				Long cpaId = answerIdList.get(p);
				entity.setCustomerProjectAnswerId(cpaId);
				//当答案ID等于“其他”选项ID时，保存文本答案
				if(cpaId == selectOther){
					entity.setAnswerValue(answerText); //文本答案
				}
				service.create(entity);
			}
		}
		
		return true;
	}
	/**
	 * 删除客户问卷原表记录
	 * @param pqId
	 * @return
	 */
	private boolean deleteCustomerAnswer(Long pqId, Long customerId, String type){
		if(pqId == null){
			return false;
		}
		//删除客户回答的答案
		CustomerAnswerDto entity = new CustomerAnswerDto();
		entity.setProjectQuestionnaireId(pqId);
		entity.setCustomerId(customerId);
		service.destroy(entity);
		
		return true;
	}
	/**
	 * 获取答案ID
	 * @param answerId
	 * @return
	 */
	private List<Long> getAnswerId(String answerId){
		List<Long> answerIdList = new ArrayList<Long>();
		JSONArray array = JSONArray.fromObject(answerId);
		for(int i = 0; i < array.size(); i++){
			answerIdList.add(array.getLong(i));
		}
		return answerIdList;
	}
	
	@Override
	public ResponseList<CustomerAnswer> selectListInfoByDto(CustomerAnswerDto dto) {
		ResponseList<CustomerAnswer> response=new ResponseList<CustomerAnswer>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<CustomerAnswer> list=service.selectListInfoByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public Response<CustomerAnswer> matchCustomer(Long projectQuestionnaireId, 
			String customerName, String customerPhone, String oldName, String oldPhone) {
		Response<CustomerAnswer> response=new Response<CustomerAnswer>();
		try {
			//判断问卷是否穿在
			ProjectQuestionnaire naire = projectQuestionnaireService
					.selectById(projectQuestionnaireId);
			if(naire == null) {
				response.fail("0000", "该问卷已删除或设置为未启用，不能进行匹配");
      			return response;
			}
			//根据客户姓名和客户手机号查询匹配的客户
      		CustomerDto entity = new CustomerDto();
      		entity.setCustomerName(customerName);
      		entity.setCustomerPhone(customerPhone);
      		entity.setProjectId(naire.getProjectId());
      		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
      		Customer cus = customerService.selectByDto(entity);
      		if(cus == null) {
      			response.fail("0000", "未查询到匹配的客户，或该客户不在此项目中");
      			return response;
      		}
      		
      		//查询该客户是否已有其他问卷
      		CustomerProjectQuestionDto cqDto = new CustomerProjectQuestionDto();
      		cqDto.setCustomerId(cus.getId());
      		cqDto.setProjectId(naire.getProjectId());
      		List<CustomerProjectQuestion> listQuestion = customerProjectQuestionService
      				.selectListByDto(cqDto);
      		if(listQuestion != null && listQuestion.size() > 0 ) {
      			response.fail("0000", "该客户回答过问卷，不能重复匹配");
      			return response;
      		}
      		//修改客户问题表信息
      		cqDto.setCustomerName(cus.getCustomerName());
      		cqDto.setCustomerPhone(cus.getCustomerPhone());
      		cqDto.setOldCustomerName(oldName);
      		cqDto.setOldCustomerPhone(oldPhone);
      		cqDto.setProjectQuestionnaireId(projectQuestionnaireId);
      		int cqCount = customerProjectQuestionService.editQuestion(cqDto);
      		if(cqCount == 0 ) {
      			response.fail("0000", "匹配客户失败");
      			return response;
      		}
      		//修改客户答案表信息
      		CustomerAnswerDto caDto = new CustomerAnswerDto();
      		caDto.setProjectQuestionnaireId(projectQuestionnaireId);
      		caDto.setCustomerId(cus.getId());
      		caDto.setCustomerName(cus.getCustomerName());
      		caDto.setCustomerPhone(cus.getCustomerPhone());
      		caDto.setOldCustomerName(oldName);
      		caDto.setOldCustomerPhone(oldPhone);
      		int caCount = customerAnswerService.editCustomer(caDto);
      		if(caCount == 0 ) {
      			response.fail("0000", "匹配客户失败");
      			return response;
      		}
      		response.setSuccess(true);
      		
      		//20180525需求：自动变成客户等级
/*			if("4".equals(cus.getIntentionLevel()) || "5".equals(cus.getIntentionLevel())) {
				CustomerDto cusDto = new CustomerDto();
				cusDto.setId(cus.getId());
				cusDto.setIntentionLevel("3");
				customerService.update(cusDto);
			}
*/
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("匹配客户失败：{}",e);
		}
		return response;
	}
}
